import { HttpException } from '@nestjs/common';

export class BasicService<T = any> {
  constructor(private readonly _repository) {}

  async create(data: T) {
    return await this._repository.create(data);
  }

  async delete(id: number) {
    return await this._repository.delete(id);
  }

  async update(id: number, data: T) {
    return await this._repository.update(id, data);
  }

  async list(): Promise<T[]> {
    return await this._repository.find();
  }

  async info(id: number): Promise<T> {
    const p = await this._repository.findOne({ where: [{ id: +id }] });
    if (!p) {
      throw this.fail(`id为${id}的数据不存在`, 401);
    }
    return p;
  }

  fail(msg: string, code: number) {
    throw new HttpException(msg, code);
  }
}
